package com.ruoyi.web.controller.video;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.video.domain.VideoDetail;
import com.ruoyi.video.service.IVideoDetailService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 模板内容Controller
 * 
 * @author ruoyi
 * @date 2025-06-07
 */
@Controller
@RequestMapping("/video/detail")
@Api("模板内容")
public class VideoDetailController extends BaseController
{
    private String prefix = "video/detail";

    @Autowired
    private IVideoDetailService videoDetailService;

//    @RequiresPermissions("video:detail:view")
    @GetMapping()
    public String detail()
    {
        return prefix + "/detail";
    }

    /**
     * 查询模板内容列表
     */
//    @RequiresPermissions("video:detail:list")
    @PostMapping("/list")
    @ResponseBody
    @ApiOperation("模板内容列表分页查询")
    public TableDataInfo list(VideoDetail videoDetail)
    {
        startPage();
        List<VideoDetail> list = videoDetailService.selectVideoDetailList(videoDetail);
        return getDataTable(list);
    }

    /**
     * 导出模板内容列表
     */
//    @RequiresPermissions("video:detail:export")
    @Log(title = "模板内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(VideoDetail videoDetail)
    {
        List<VideoDetail> list = videoDetailService.selectVideoDetailList(videoDetail);
        ExcelUtil<VideoDetail> util = new ExcelUtil<VideoDetail>(VideoDetail.class);
        return util.exportExcel(list, "模板内容数据");
    }

    /**
     * 新增模板内容
     */
    @GetMapping("/add")
    public String add(Model model,Integer templateId)
    {
        model.addAttribute("templateId",templateId);
        return prefix + "/add";
    }

    /**
     * 新增保存模板内容
     */
//    @RequiresPermissions("video:detail:add")
    @Log(title = "模板内容", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @ApiOperation("新增模板内容")
    public AjaxResult addSave(VideoDetail videoDetail)
    {
        Float speechRate = videoDetail.getSpeechRate();
        if(speechRate == null){
            speechRate = 1.2f;
        }
        if(videoDetail.getIsDefault() == 1){
            String API_KEY = "sk-73bee8e4fc8644eb99a76d302fbe40f9"; // 替换为你的API Key
            String MODEL = "cosyvoice-v1";      // 模型版本
            String VOICE = "longwan";   // 音色（参考音色列表[1](@ref)）

            SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                    .apiKey(API_KEY)
                    .model(MODEL)
                    .voice(VOICE)
                    .speechRate(speechRate)
                    .build();
            SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);

            String pre = System.currentTimeMillis() + ".mp3";
//            String path = "C:\\Files\\video\\" + pre;
        String path = "/www/wwwroot/qy.xunzhunshuju.com/template/" + pre;

            ByteBuffer audioData = synthesizer.call(videoDetail.getText());

            try (FileOutputStream fos = new FileOutputStream(path)) {
                fos.write(audioData.array());
                videoDetail.setFilePath("https://qy.xunzhunshuju.com/template/" + pre);
                System.out.println("✅ 合成成功！文件保存至: " + path);
                System.out.println("🔧 请求ID: " + synthesizer.getLastRequestId());
            } catch (Exception ex) {
                System.err.println("❌ 保存失败: " + ex.getMessage());
            }
        }
        videoDetail.setCreateTime(new Date());
        return toAjax(videoDetailService.insertVideoDetail(videoDetail));
    }

    /**
     * 修改模板内容
     */
    @RequiresPermissions("video:detail:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        VideoDetail videoDetail = videoDetailService.selectVideoDetailById(id);
        mmap.put("videoDetail", videoDetail);
        return prefix + "/edit";
    }

    /**
     * 修改保存模板内容
     */
//    @RequiresPermissions("video:detail:edit")
    @Log(title = "模板内容", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @ApiOperation("修改模板内容")
    public AjaxResult editSave(VideoDetail videoDetail)
    {
        Float speechRate = videoDetail.getSpeechRate();
        if(speechRate == null){
            speechRate = 1.2f;
        }
        if(videoDetail.getIsDefault() == 1){
            String API_KEY = "sk-73bee8e4fc8644eb99a76d302fbe40f9"; // 替换为你的API Key
            String MODEL = "cosyvoice-v1";      // 模型版本
            String VOICE = "longwan";   // 音色（参考音色列表[1](@ref)）

            SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                    .apiKey(API_KEY)
                    .model(MODEL)
                    .voice(VOICE)
                    .speechRate(speechRate)
                    .build();
            SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);

            String pre = System.currentTimeMillis() + ".mp3";
//            String path = "C:\\Files\\video\\" + pre;
            String path = "/www/wwwroot/qy.xunzhunshuju.com/template/" + pre;

            ByteBuffer audioData = synthesizer.call(videoDetail.getText());

            try (FileOutputStream fos = new FileOutputStream(path)) {
                fos.write(audioData.array());
                videoDetail.setFilePath("https://qy.xunzhunshuju.com/template/" + pre);
                System.out.println("✅ 合成成功！文件保存至: " + path);
                System.out.println("🔧 请求ID: " + synthesizer.getLastRequestId());
            } catch (Exception ex) {
                System.err.println("❌ 保存失败: " + ex.getMessage());
            }
        }
        videoDetail.setUpdateTime(new Date());
        return toAjax(videoDetailService.updateVideoDetail(videoDetail));
    }

    /**
     * 删除模板内容
     */
//    @RequiresPermissions("video:detail:remove")
    @Log(title = "模板内容", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    @ApiOperation("删除模板内容")
    public AjaxResult remove(String ids)
    {
        return toAjax(videoDetailService.deleteVideoDetailByIds(ids));
    }
}
